//
//  MXFooderRecordController.m
//  HNBaseProject
//
//  Created by xujie on 2024/6/4.
//

#import "MXFooderRecordController.h"
#import "MxPublicNav.h"
#import "MXFooderRecordCell.h"
#import "MXFooderPlanModel.h"
@interface MXFooderRecordController () <MxNavigationViewDelegate,UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) MxPublicNav *nav;
@property (nonatomic, strong) UITableView *listTab;
@property (nonatomic, assign) NSInteger   page;
@property (nonatomic, strong) NSMutableArray *listArray;
@end

@implementation MXFooderRecordController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#f8f8f8"];
    self.page = 1;
    self.listArray = [[NSMutableArray alloc] init];
    [self createUI];
    [self getFoodList];
    
    MJWeakSelf
    self.listTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf getFoodList];
    }];
    
    MJRefreshAutoStateFooter * footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf getFoodList];
    }];
}

- (void)getFoodList {

    MJWeakSelf
    NSDictionary *param = @{@"deviceId":self.model.ID,
                            @"pageNum":[NSString stringWithFormat:@"%ld",self.page],
                            @"pageSize":@"20"};
    [self.view makeToastActivity];
    NSString *urlStr = [NSString stringWithFormat:@"%@?pageNum=%@&pageSize=%@&deviceId=%@",@"api/app/appFeedingRecord/list",[NSString stringWithFormat:@"%ld",self.page],@"20",self.model.ID];
    [[DCHttpClient shareClient] requestWithPath:urlStr params:@{} httpMethod:DCHttpRequestPost sucess:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary * dict = [responseObject mj_JSONObject];
        [weakSelf.view hideToastActivity];
        if (dict[DC_ResultCode_Key] && [dict[DC_ResultCode_Key] integerValue] == DC_Result_Success) {
            [weakSelf.listTab.mj_footer endRefreshing];
            [weakSelf.listTab.mj_header endRefreshing];
            if (weakSelf.page == 1) {
                [weakSelf.listArray removeAllObjects];
            }
            NSArray *dataArray =  [NSArray modelArrayWithClass:[MXFooderPlanModel class] json:dict[@"data"][@"list"]];
            [weakSelf.listArray addObjectsFromArray:dataArray];
            [weakSelf.listTab reloadData];
            
            if (dataArray.count < 20) {
                [self.listTab.mj_footer endRefreshingWithNoMoreData];
            }
            
            self.listTab.mj_footer.hidden = self.listArray.count == 0;
        } else {

            [weakSelf.view xjmakeToast:dict[DC_ResultMsg_Key]];
            [weakSelf.listTab.mj_footer endRefreshing];
            [weakSelf.listTab.mj_header endRefreshing];
        }
    } failture:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [weakSelf.view hideToastActivity];
        [weakSelf.listTab.mj_footer endRefreshing];
        [weakSelf.listTab.mj_header endRefreshing];
    }];
}

- (void)createUI {
    self.nav = [[MxPublicNav alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kNavBarHeight)];
    self.nav.titleLab.text = @"喂食记录";
    self.nav.delegate = self;
    [self.view addSubview:self.nav];
    
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.text = @"设备无外网时，无喂食记录，但设备仍会正常出食~";
    titleLab.font =  PFRFontMedium(12);
    titleLab.textColor = [UIColor colorWithHexString:@"#818181"];
    [self.view addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.offset(kNavBarHeight + 30);
    }];
    
    UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fooder_notice"]];
    [self.view addSubview:icon];
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(titleLab);
        make.right.mas_equalTo(titleLab.mas_left).offset(-7);
        make.height.width.mas_equalTo(16);
    }];
    
    [self.view addSubview:self.listTab];
    [self.listTab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.bottom.offset(0);
        make.top.mas_equalTo(titleLab.mas_bottom).offset(20);
    }];
}

#pragma mark - ________ UITableView ________

- (UITableView *)listTab {
    
    if (nil == _listTab) {
        _listTab = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _listTab.backgroundColor = [UIColor colorWithHexString:@"#f8f8f8"];
        _listTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        _listTab.delegate = self;
        _listTab.dataSource = self;
        _listTab.rowHeight = 70.0;
        _listTab.showsVerticalScrollIndicator = NO;
        _listTab.showsHorizontalScrollIndicator= NO;
        [_listTab registerClass:[MXFooderRecordCell class] forCellReuseIdentifier:NSStringFromClass([MXFooderRecordCell class])];
        if (@available(iOS 11.0, *)) {
            _listTab.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _listTab.sectionHeaderTopPadding = 0;
        }
    }
    return _listTab;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MXFooderPlanModel *model = self.listArray[indexPath.section];
    MXFooderRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MXFooderRecordCell class])];
    MXFooderPlanDetailModel *listModel = model.appFeedingRecordListDtoList[indexPath.row];
    [cell reloadCellWithModel:listModel];
    return cell;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    MXFooderPlanModel *model = self.listArray[section];
    return model.appFeedingRecordListDtoList.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listArray.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 40)];
    UILabel *titleLab = [[UILabel alloc] init];
    MXFooderPlanModel *model = self.listArray[section];
    titleLab.text = [NSString stringWithFormat:@"%@ 星期%@",model.date,[self getHansDayWithNum:model.dayOfWeek]];//@"2024.04.27 星期六";
    titleLab.font = PFRFontMedium(15);
    [headV addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(18);
//        make.centerY.mas_equalTo(headV);
        make.bottom.offset(0);
    }];
    return headV;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40.0;
}

- (void)leftTap {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self dc_navBarHidden:YES];
}

- (NSString *)getHansDayWithNum:(NSString *)num {
    NSString *numStr = @"一";
    if ([num isEqualToString:@"1"]) {
        numStr = @"一";
    } else if ([num isEqualToString:@"2"]) {
        numStr = @"二";
    } else if ([num isEqualToString:@"3"]) {
        numStr = @"三";
    } else if ([num isEqualToString:@"4"]) {
        numStr = @"四";
    } else if ([num isEqualToString:@"5"]) {
        numStr = @"五";
    } else if ([num isEqualToString:@"6"]) {
        numStr = @"六";
    } else if ([num isEqualToString:@"7"]) {
        numStr = @"日";
    }
    return numStr;
}

@end
